package my.net.server;

import java.io.UnsupportedEncodingException;

import my.net.server.service.PushServer;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;

public class Encoder extends OneToOneEncoder {

	@Override
	protected Object encode(ChannelHandlerContext ctx, Channel channel,
			Object msg) throws Exception {
		if (!(msg instanceof String)) {
			return msg;
		}
		String json = (String) msg;

		byte[] dataByte;
		try {
			dataByte = json.getBytes("UTF-8");
			ChannelBuffer channelBuffer = ChannelBuffers
					.buffer(dataByte.length);
			channelBuffer.writeBytes(dataByte);
			return channelBuffer;
		} catch (UnsupportedEncodingException e1) {
			PushServer.close(channel);
		}
		return null;
	}

}
